package com.xiao.androidcompose01.screen.main

import android.Manifest
import android.view.ViewGroup
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Place
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
import cafe.adriel.voyager.koin.koinScreenModel
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabOptions
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
import com.tencent.tencentmap.mapsdk.maps.MapView
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition
import com.tencent.tencentmap.mapsdk.maps.model.LatLng
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions
import com.xiao.androidcompose01.LocalAccountData
import com.xiao.androidcompose01.ui.theme.MainColor
import com.xiao.androidcompose01.viewmodel.TencentMapModel
import com.xiao.androidcompose01.viewmodel.TencentRoomModel
import com.xiao.androidcompose01.weight.click

class MapTab : Tab {
   override val options: TabOptions
      @Composable
      get(){
         val title = "地图"
         val icon = rememberVectorPainter(Icons.Filled.Place)
         
         return remember {
            TabOptions(
               index = 0u,
               title = title,
               icon = icon
            )
         }
      }
   
   @OptIn(ExperimentalPermissionsApi::class)
   @Composable
   override fun Content() {
      val accountData = LocalAccountData.current
      val lifecycleOwner = LocalLifecycleOwner.current
      val context = LocalContext.current
      val tencentRoomModel = koinScreenModel<TencentRoomModel>()
      var mapView by remember { mutableStateOf<MapView?>(null) }
      val permissionState = rememberMultiplePermissionsState(
         permissions = listOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
         )
      )
      LaunchedEffect(Unit) {
         println("申请定位权限")
         permissionState.launchMultiplePermissionRequest()
      }
      Box(modifier = Modifier.fillMaxSize()){
         AndroidView(factory = {
            val map = MapView(it)
            map.layoutParams = ViewGroup.LayoutParams(
               ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            mapView = map
            map
         }, modifier = Modifier.fillMaxSize(), onReset = {
         }, onRelease = {
         }, update = {
            if (!accountData.isParent()){
               mapView?.let {
                  println("定位权限")
                  tencentRoomModel.startLocation(accountData,it)
               }
            }else{
               mapView?.let {
                  tencentRoomModel.initMap(accountData,it)
               }
            }
         })
         if (accountData.isParent()){
            Image(
               Icons.Default.Place,null,
               colorFilter = ColorFilter.tint(MainColor),
               modifier = Modifier
                  .align(Alignment.BottomEnd)
                  .padding(bottom = 100.dp, end = 20.dp)
                  .size(60.dp)
                  .background(Color.Red.copy(0.5f), CircleShape)
                  .padding(15.dp)
                  .click(true,{
                     tencentRoomModel.updateShowLocation().let {
                        if (it.isNotBlank()){
                           Toast.makeText(context,it,Toast.LENGTH_LONG).show()
                        }
                     }
                  })
            )
         }
         
      }
      
      DisposableEffect(lifecycleOwner) {
         val lifecycleObserver = object : LifecycleEventObserver {
            
            override fun onStateChanged(
               source: LifecycleOwner,
               event: Lifecycle.Event
            ) {
               when (event) {
                  Lifecycle.Event.ON_RESUME -> {
                     mapView?.onResume()
                  }
                  Lifecycle.Event.ON_PAUSE -> {
                     mapView?.onPause()
                  }
                  Lifecycle.Event.ON_START ->{
                     mapView?.onStart()
                  }
                  Lifecycle.Event.ON_STOP ->{
                     mapView?.onStop()
                  }
                  else -> {}

                  
               }
            }
         }
         
         lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
         onDispose {
            lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
            mapView?.onDestroy()
         }
      }
   }
   
   @Preview
   @Composable
   private fun ContentPreview() {
      Content()
   }
   
}